<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/";
%>
<!DOCTYPE html>
<html>
<head>
	<base href="<%=basePath%>">
<meta charset="UTF-8">

<link href="../../jquery/bootstrap_3.3.0/css/bootstrap.min.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="../../jquery/jquery-1.11.1-min.js"></script>
<script type="text/javascript" src="../../jquery/bootstrap_3.3.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="../../jquery/bs_pagination/jquery.bs_pagination.min.css">
<script type="text/javascript" src="../../jquery/bs_pagination/jquery.bs_pagination.min.js"></script>
<script type="text/javascript" src="../../jquery/bs_pagination/en.js"></script>

<script type="text/javascript">
	$(function(){
		//定制字段
		$("#definedColumns > li").click(function(e) {
			//防止下拉菜单消失
	        e.stopPropagation();
	    });


		//对创建人下拉框赋值
		function getSysUserList(){
			$.ajax({

				url : "sysUser/getSysUserList",
				type : "get",
				dataType : "json",
				success : function (data) {

					var html = "<option></option>";

					//遍历出来的每一个n，就是每一个user对象
					$.each(data,function (i,n) {
						html += "<option value='"+n.userId+"'>"+n.userName+"</option>";
					});

					$("#create-chcCreateBy").html(html);
					$("#edit-chcCreateBy").html(html);
					$("#create-chcDueTo").html(html);
					$("#designate-chcDueTo").html(html);

				}

			});
		}
		getSysUserList();

        //为全选的复选框绑定事件，触发全选操作
        $("#qx").click(function () {

            $("input[name=xz]").prop("checked",this.checked);

        });


        //制定计划页面makeplan
		$("#makePlanBtn").click(function () {
			var $xz = $("input[name=xz]:checked");
            if($xz.length==0){
                alert("请选择需要制定计划的销售机会");
            }else if($xz.length>1){
                alert("只能选择一条制定计划的销售机会");
                //肯定只选了一条
            }else {
                window.location.href = 'workbench/marketing/makeplan.jsp?chcId=' + $xz.val();
            }
            });

        //为修改按钮绑定事件，打开修改操作的模态窗口
        $("#editBtn").click(function () {
            var $xz = $("input[name=xz]:checked");
            if($xz.length==0){
                $("#marketingEditForm")[0].reset();
                alert("请选择需要修改的记录");
                return
            }else if($xz.length>1){
                $("#marketingEditForm")[0].reset();
                alert("只能选择一条记录进行修改");
                return
                //肯定只选了一条
            }else{
                var custNo = $xz.val();
                $.ajax({
                    url : "customer/getCustomerByCustNo",
                    data : {
                        "custNo" : custNo
                    },
                    type : "get",
                    dataType : "json",
                    success : function (data) {

                        //处理单条customer,并赋值给各标签

						if (data.success){
                            $("#edit-custNo").val(data.customer.custNo);
                            $("#edit-custName").val(data.customer.custName);
                            $("#edit-commonCreater").val(data.customer.custCreater);
                            $("#edit-custRegion").val(data.customer.custRegion);
                            $("#edit-custManagerName").val(data.customer.custManagerName);
                           // $("#edit-custCreater").val(data.customer.custCreater);
                            $("#edit-custLevel").val(data.customer.custLevel);
                            $("#edit-custLevelLabel").val(data.customer.custLevelLabel);
                            $("#edit-custCredit").val(data.customer.custCredit);
                            $("#edit-custAddr").val(data.customer.custAddr);
                            $("#edit-custZip").val(data.customer.custZip);
                            $("#edit-custTel").val(data.customer.custTel);
                            $("#edit-custFax").val(data.customer.custFax);
                            $("#edit-custWebsite").val(data.customer.custWebsite);
                            $("#edit-custLicenceNo").val(data.customer.custLicenceNo);
                            $("#edit-custChieftain").val(data.customer.custChieftain);
                            $("#edit-custBankroll").val(data.customer.custBankroll);
                            $("#edit-custTurnover").val(data.customer.custTurnover);
                            $("#edit-custBank").val(data.customer.custBank);
                            $("#edit-custBankAccount").val(data.customer.custBankAccount);
                            $("#edit-custLocalTaxNo").val(data.customer.custLocalTaxNo);
                            $("#edit-custNationalTaxNo").val(data.customer.custNationalTaxNo);

                            //所有的值都填写好之后，打开修改操作的模态窗口
                            $("#editCustomerModal").modal("show");
						}else {
                            $("#marketingEditForm")[0].reset();
                            $("#editCustomerModal").modal("hide");
						}

                    }
                })
            }
        });

        //为更新按钮绑定事件，执行市场活动的修改操作
        $("#updateBtn").click(function () {

            $.ajax({

                url : "customer/update",
                data : {
                    "custNo" : $.trim($("#edit-custNo").val()),
                    "custName" : $.trim($("#edit-custName").val()),
                    "custRegion" : $.trim($("#edit-custRegion").val()),
                    "custManagerName" : $.trim($("#edit-custManagerName").val()),
                    "custCreater" : $.trim($("#edit-custCreater").val()),
					"commonCreater" : $.trim($("#edit-commonCreater").val()),
                    "custLevel" : $.trim($("#edit-custLevel").val()),
                    "custLevelLabel" : $.trim($("#edit-custLevelLabel").val()),
                    "custCredit" : $.trim($("#edit-custCredit").val()),
                    "custAddr" : $.trim($("#edit-custAddr").val()),
                    "custZip" : $.trim($("#edit-custZip").val()),
                    "custTel" : $.trim($("#edit-custTel").val()),
                    "custFax" : $.trim($("#edit-custFax").val()),
                    "custWebsite" : $.trim($("#edit-custWebsite").val()),
                    "custLicenceNo" : $.trim($("#edit-custLicenceNo").val()),
                    "custChieftain" : $.trim($("#edit-custChieftain").val()),
                    "custBankroll" : $.trim($("#edit-custBankroll").val()),
                    "custTurnover" : $.trim($("#edit-custTurnover").val()),
                    "custBank" : $.trim($("#edit-custBank").val()),
                    "custBankAccount" : $.trim($("#edit-custBankAccount").val()),
                    "custLocalTaxNo" : $.trim($("#edit-custLocalTaxNo").val()),
                    "custNationalTaxNo" : $.trim($("#edit-custNationalTaxNo").val())
                },
                type : "post",
                dataType : "json",
                success : function (data) {
                    if(data.success){
                        /*
                            修改操作后，应该维持在当前页，维持每页展现的记录数
                         */
                        pageList($("#developPage").bs_pagination('getOption', 'currentPage')
                            ,$("#developPage").bs_pagination('getOption', 'rowsPerPage'));
                        $("#marketingEditForm")[0].reset();
                        //关闭修改操作的模态窗口
                        $("#editActivityModal").modal("hide");
                    }else{
                        alert("修改市场活动失败");
                    }
                }
            })
        });


        $("#designateOpenBtn").click(function () {
			var $xz = $("input[name=xz]:checked");
			if($xz.length==0){
				alert("请选择需要修改的记录");
			}else if($xz.length>1){
				alert("只能选择一条记录进行修改");
				//肯定只选了一条
			}else{
				var custNo = $xz.val();
				$.ajax({
					url : "marketing/getCustomerByCustNo/"+custNo,
					type : "get",
					dataType : "json",
					success : function (data) {

						//处理单条customer,并赋值给各标签
						if (data.success){
							$("#designate-custNo").val(data.customer.custNo);
							$("#designate-custName").val(data.customer.custName);
							$("#designate-commonCreater").val(data.customer.custCreater);
							//所有的值都填写好之后，打开修改操作的模态窗口
							$("#designateManagerModal").modal("show");
						}else {
							$("#designateManagerForm")[0].reset();
							$("#designateManagerModal").modal("hide");
						}

					}
				})
			}
		});

        //指派执行经理或者主管
		$("#designateBtn").click(function () {
			$.ajax({

				url : "marketing/update",
				data : {
					"custNo" : $.trim($("#designate-custNo").val()),
					"custName" : $.trim($("#designate-custName").val()),
					"custManagerName" : $.trim($("#designate-custManagerName").val()),
					"custCreater" : $.trim($("#designate-commonCreater").val()),
				},
				type : "post",
				dataType : "json",
				success : function (data) {
					if(data.success){
						pageList($("#developPage").bs_pagination('getOption', 'currentPage')
								,$("#developPage").bs_pagination('getOption', 'rowsPerPage'));
						$("#designateManagerForm")[0].reset();
						//关闭修改操作的模态窗口
						$("#designateManagerModal").modal("hide");
					}else{
						alert("指派失败");
					}
				}
			})
		});

         //为删除按钮绑定事件，执行市场活动删除操作
        $("#deleteBtn").click(function () {
            //找到复选框中所有挑√的复选框的jquery对象
            var $xz = $("input[name=xz]:checked");
            if($xz.length==0){
                alert("请选择需要删除的记录");
                //肯定选了，而且有可能是1条，有可能是多条
            }else{
                if(confirm("确定删除所选中的记录吗？")){
                    //url:workbench/activity/delete.do?id=xxx&id=xxx&id=xxx
                    //拼接参数
                    var param = "";
                    //将$xz中的每一个dom对象遍历出来，取其value值，就相当于取得了需要删除的记录的id
                    for(var i=0;i<$xz.length;i++){
                        param += "custNo="+$($xz[i]).val();
                        //如果不是最后一个元素，需要在后面追加一个&符
                        if(i<$xz.length-1){
                            param += "&";
                        }
                    }
                    $.ajax({
                        url : "customer/delete",
                        data : param,
                        type : "post",
                        dataType : "json",
                        success : function (data) {
                            /*
                                data
                                    {"success":true/false}
                             */
                            if(data.success){
                                //删除客户成功之后，会进行一次页面刷新，刷新出保存的用户，根据创建时间来进行排序
                                pageList(1,$("#developPage").bs_pagination('getOption', 'rowsPerPage'));
                            }else{
                                alert("删除失败");
                            }
                        }
                    })
                }
            }
        });

        //给执行计划按钮添加事件
        $("#startPlanBtn").click(function () {
            var $xz = $("input[name=xz]:checked");
            if($xz.length==0){
                alert("请选择需要执行的记录");
            }else if($xz.length>1){
                alert("只能选择一条执行")
            }else {
                window.location.href = 'workbench/marketing/execute.jsp?chcId=' + $xz.val();
            }
        });

        $("#successBtn").click(function () {
            var $xz = $("input[name=xz]:checked");
            if($xz.length==0){
                alert("请选择需要开发成功的记录");
            }else if($xz.length>1){
                alert("只能选择一条开发成功")
            }else {
                $.ajax({
                    url: "execute/saveCustomer",
                    data: {
                        "chcId": $xz.val(),
                        "custName": $.trim($("#executeChcCustName").text()),
                        "custManagerName": $.trim($("#executeChcDueTo").text()),
                        "custCreater": $.trim($("#executeChcCreateBy").text()),
                        "custTel": $.trim($("#executeChcTel").text())
                    },
                    type: "post",
                    dataType: "json",
                    success: function (data) {
                        if (data.success) {
                            alert("添加客户成功")
                            window.location.href = "/workbench/marketing/main.jsp";
                        } else {
                            alert("添加客户失败");
                        }
                    }
                })
            }
        });

        //为查询按钮绑定事件(暂未开发)
        $("#searchBtn").click(function () {
            /*
                点击查询按钮的时候，我们应该将搜索框中的信息保存起来,保存到隐藏域中
             */
            $("#hidden-name").val($.trim($("#search-name").val()));
            var name = $("#search-name").val();
            pageList(1,2);
        });

        //因为动态生成的元素，是不能够以普通绑定事件的形式来进行操作的
        $("#developBody").on("click",$("input[name=xz]"),function () {

            $("#qx").prop("checked",$("input[name=xz]").length==$("input[name=xz]:checked").length);

        });

        //同意申请开发失败（客户主管）(开发失败)
		$("#failBtn").click(function () {
			var $xz = $("input[name=xz]:checked");
			if($xz.length==0){
				alert("请选择需要开发失败的记录");
			}else if($xz.length>1) {
				alert("只能选择一条开发失败的记录")
			}else {
				$.ajax({
					url : "develop/fail",
					data : {
						"chcId":$xz.val()
					},
					type : "post",
					dataType : "json",
					success : function (data) {
						if(data.success){
							pageList(1,$("#developPage").bs_pagination('getOption', 'rowsPerPage'));
						}else{
							alert("同意申请开发失败失败");
						}
					}
				})
			}
		});

		//不同意申请开发失败（客户主管）(开发失败)
		$("#noFailBtn").click(function () {
			var $xz = $("input[name=xz]:checked");
			if($xz.length==0){
				alert("请选择一条记录");
			}else if($xz.length>1) {
				alert("只能选择一条记录")
			}else {
				$.ajax({
					url : "develop/noFail",
					data : {
						"chcId":$xz.val()
					},
					type : "post",
					dataType : "json",
					success : function (data) {
						if(data.success){
							pageList(1,$("#developPage").bs_pagination('getOption', 'rowsPerPage'));
						}else{
							alert("不同意申请开发失败失败");
						}
					}
				})
			}
		});


        //进入客户管理页面，我们需要进行一次分页查询
        pageList(1,2);

		//用来处理分页请求
		function pageList(pageNo,pageSize) {

			//将全选的复选框的√干掉
			$("#qx").prop("checked",false);
			$.ajax({

						url: "develop/"+pageNo+"/"+pageSize,
						type: "get",
						dataType: "json",
						success: function (data) {

							var html = "";

							//每一个n就是每一个市场活动对象
							$.each(data.dataList, function (i, n) {

                                if (n.chcStatus != "已归档"){
                                    html += '<tr class="active">';
                                    html += '<td><input type="checkbox" name="xz" value="'+n.chcId+'"/></td>';
                                    html += '<td>'+n.chcCustName+'</td>';
                                    html += '<td>'+n.chcTitle+'</td>';
                                    html += '<td>'+n.chcLinkman+'</td>';
                                    html += '<td>'+n.chcTel+'</td>';
                                    html += '<td>'+new Date(n.chcCreateDate).format("yyyy-MM-dd")+'</td>';
                                    html += '<td>'+n.chcStatus+'</td>';
                                    html += '</tr>';
                                }else {
                                    html += '<tr class="active">';
                                    html += '<td><a style="text-decoration: none; cursor: pointer;" onclick="window.location.href=\'workbench/marketing/check.jsp?chcId='+n.chcId+'\';">查看</a></td>';
                                    html += '<td>' + n.chcCustName + '</td>';
                                    html += '<td>' + n.chcTitle + '</td>';
                                    html += '<td>' + n.chcLinkman + '</td>';
                                    html += '<td>' + n.chcTel + '</td>';
                                    html += '<td>' + new Date(n.chcCreateDate).format("yyyy-MM-dd") + '</td>';
                                    html += '<td>' + n.chcStatus + '</td>';
                                    html += '</tr>';
                                }

							});
							$("#developBody").html(html);
							//计算总页数
							var totalPages = data.total%pageSize==0?data.total/pageSize:parseInt(data.total/pageSize)+1;
							//数据处理完毕后，结合分页查询，对前端展现分页信息
							$("#developPage").bs_pagination({
								currentPage: pageNo, // 页码
								rowsPerPage: pageSize, // 每页显示的记录条数
								maxRowsPerPage: 20, // 每页最多显示的记录条数
								totalPages: totalPages, // 总页数
								totalRows: data.total, // 总记录条数

								visiblePageLinks: 3, // 显示几个卡片

								showGoToPage: true,
								showRowsPerPage: true,
								showRowsInfo: true,
								showRowsDefaultInfo: true,

								//该回调函数时在，点击分页组件的时候触发的
								onChangePage: function (event, data) {
									pageList(data.currentPage, data.rowsPerPage);
								}
							});

						}
					}
			)}


		Date.prototype.format = function(fmt) {
			var o = {
				"M+" : this.getMonth() + 1, // 月份
				"d+" : this.getDate(), // 日
				"h+" : this.getHours(), // 小时
				"m+" : this.getMinutes(), // 分
				"s+" : this.getSeconds(), // 秒
				"q+" : Math.floor((this.getMonth() + 3) / 3), // 季度
				"S" : this.getMilliseconds()
				// 毫秒
			};
			if (/(y+)/.test(fmt))
				fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "")
						.substr(4 - RegExp.$1.length));
			for ( var k in o)
				if (new RegExp("(" + k + ")").test(fmt))
					fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k])
							: (("00" + o[k]).substr(("" + o[k]).length)));
			return fmt;
		}
	});

</script>
</head>
<body>
    <%--根据用户名查询用户隐藏域--%>
    <input type="hidden" id="hidden-name"/>
	<input type="hidden" id="designate-custNo">

	<div>
		<div style="position: relative; left: 10px; top: -10px;">
			<div class="page-header">
				<h3>客户开发计划列表</h3>
			</div>
		</div>
	</div>
	
	<div style="position: relative; top: -20px; left: 0px; width: 100%; height: 100%;">
	
		<div style="width: 100%; position: absolute;top: 5px; left: 10px;">
		
			<div class="btn-toolbar" role="toolbar" style="height: 80px;">
				<form class="form-inline" role="form" style="position: relative;top: 8%; left: 5px;">
				  
				  <div class="form-group">
				    <div class="input-group">
				      <div class="input-group-addon">客户名称</div>
				      <input class="form-control" type="text" id="search-name">
				    </div>
				  </div>

				  <button type="submit" class="btn btn-default" id="searchBtn">查询</button>
				  
				</form>
			</div>
			<div class="btn-toolbar" role="toolbar" style="background-color: #F7F7F7; height: 50px; position: relative;top: 5px;">
				<div class="btn-group" style="position: relative; top: 18%;">
					<shiro:hasPermission name="sell:makeplan">
					   <button type="button" class="btn btn-default" data-toggle="modal" data-target="#makePlanBtnModal" id="makePlanBtn"><span class="glyphicon glyphicon-book"></span> 制定计划</button>
					</shiro:hasPermission>
					<shiro:hasPermission name="sell:executeplan">
					   <button type="button" class="btn btn-default" data-toggle="modal" data-target="#startPlanModal" id="startPlanBtn"><span class=" glyphicon glyphicon-phone-alt"></span> 执行计划</button>
					</shiro:hasPermission>
					<shiro:hasPermission name="sell:stopDevelop">
					<button type="button" class="btn btn-danger"  id="failBtn"><span class="glyphicon glyphicon-plus-sign"></span> 同意申请开发失败</button>
					</shiro:hasPermission>
					<shiro:hasPermission name="sell:continueDevelop">
						<button type="button" class="btn btn-danger"  id="noFailBtn"><span class="glyphicon glyphicon-minus-sign"></span> 不同意申请开发失败</button>
					</shiro:hasPermission>
					<button type="button" class="btn btn-danger"  id="successBtn"><span class="glyphicon glyphicon-ok"></span> 开发成功</button>
				</div>
			</div>

			<div style="position: relative;top: 10px;">
				<table class="table table-hover">
					<thead>
					<tr style="color: #B3B3B3;">
						<td><input type="checkbox" id="qx" /></td>
						<td>客户名称</td>
						<td>概要</td>
						<td>联系人</td>
						<td>联系人电话</td>
						<td>创建时间</td>
						<td>状态</td>
					</tr>
					</thead>
					<tbody id="developBody">
					</tbody>
				</table>
			</div>
			
			<div style="height: 50px; position: relative;top: 30px;">
				<div id="developPage"></div>
			</div>

		</div>
		
	</div>
</body>
</html>